<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="文件地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            name="file"
            v-decorator="['file', {}]"
            :action="uploadAction"
            :headers="headers"
            :fileList="fileList"
            :multiple="true"
            @change="handleChange"
             accept=".mp4,.jpg,.gif,.png,.jpeg"
            :beforeUpload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 上传附件 </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
    <a-form-item label="提示" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <span style="color: #0000FF"><a-icon type="exclamation-circle" />小屏（方杆）单张图片不要超过100KB，大屏单张不要超过3M，视频不要超过300M。支持mp4、jpg、gif、png、jpeg格式上传</span>
    </a-form-item>
  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import { getUploadFileList,getFilePaths } from '@/utils/commonUploadFile.js'
  import Vue from 'vue'
  export default {
    name: "GlrResourceModal",
    components: {
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        visible: false,
        headers: {},
        fileList: [],
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          filename: {rules: [
          ]},
          filepath: {rules: [
          ]},
          filetype: {rules: [
          ]},
          filesize: {rules: [
          ]},
          fileid: {rules: [
          ]},
          fileMd5: {rules: [
          ]},
          filePlayTime: {rules: [
          ]},
          sysCompanyCode: {rules: [
          ]},
        },
        url: {
          add: "/glr/glrResource/addLedResource",
          edit: "/glr/glrResource/edit",
          fileUpload: window._CONFIG['domianURL']+"/glr/glrResource/ledUpload",
        }
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token};
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        let currFileList = getUploadFileList(this.model.filePath);
        console.info(currFileList);
        this.fileList = [...currFileList]
        this.$forceUpdate();
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'filename','filepath','filetype','filesize','fileid','fileMd5','filePlayTime','sysCompanyCode'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;

        if (that.fileList.length==0){
          that.$message.warning("没有上传的文件");
          return;
        }else {
          if ("done"==that.fileList[0].status){

          }else {
            that.$message.warning("文件正在上传中,请等待...");
            return;
          }
        }

        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.filePath = getFilePaths(this.fileList);
            console.info(formData.filePath);
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'filename','filepath','filetype','filesize','fileid','fileMd5','filePlayTime','sysCompanyCode'))
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.fileList = info.fileList;
          return
        }
        if (info.file.status === 'removed') {
          this.fileList=info.fileList;
          return
        }
        if (info.file.status === 'done') {
          this.fileList = info.fileList;
          var response = info.file.response;
          if (!response.success) {
            this.$message.warning(response.message);
          }
        }
      },
      beforeUpload(file) {
        var isJPG=false;
        var fileType=file.type.toLowerCase();
        if(fileType.indexOf('jpeg')!=-1){
          isJPG=true;
        }else if(fileType.indexOf('png')!=-1){
          isJPG=true;
        }else if(fileType.indexOf('mp4')!=-1) {
          isJPG=true;
        }else if(fileType.indexOf('jpg')!=-1) {
          isJPG=true;
        }else if(fileType.indexOf('gif')!=-1) {
          isJPG=true;
        }
        if(!isJPG){
          this.$message.error('只能上传mp4、jpg、gif、png、jpeg格式的文件,单个文件最大不能超过200MB');
          this.fileList=[];
          return false;
        }
        var isLt2M = true;
        if ((file.size / 1024 / 1024)>200) {
          this.$message.error('单个文件最大不能超过200MB!');
          this.fileList=[];
          return false;
        }
        if(isJPG && isLt2M){
          return true;
        }
      },
    }
  }
</script>